package mc.support.web.action.invoke;

import mc.support.web.action.ActionWrapper;
import mc.support.web.action.aware.FileUploadAware;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yun    <br/>
 * Date: 2014-04-21  <br/>
 */
public class FileUploadActionInvoker extends InvokerSupport implements Invoker<FileUploadAware> {

    @Override
    public int getPriority() {
        return ActionPriority.FILE_UPLOAD;
    }

    @Override
    public Class<FileUploadAware> getAwareClass() {
        return FileUploadAware.class;
    }

    @Override
    public Object invoke(FileUploadAware aware, ActionWrapper action, Map<String, Object> params) throws Exception {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold( aware.getMaxMemSize() );
//        factory.setRepository(yourTempDirectory);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax( aware.getMaxReqSize() );
        HttpServletRequest request = getHttpReq( params );
        List<FileItem> items = upload.parseRequest(request);
        for ( FileItem item : items ) {
            if ( item.isFormField() ) {
                params.put( item.getFieldName(), item.getString() );
            }
        }
        return aware.doUpload( items, params );
    }

    @Override
    public ResultWriter getResultWriter() {
        return ResultWriter.text;
    }

}
